avatar Bite 179. Strip comments from Python code

In this Bite you will strip off all comments from some Python source code. Complete strip_comments that takes some multiline code string and strip out:

  • Single line comments = lines that start with #.
  • PEP8-compliant inline comments, so code followed by 2 spaces, a #, a space and comment.
  • Multiline comments / docstrings ("""my\ncomment"""), which could be non indented (at the module level) or indented in a function/ method. You can assume these have always 3 double, not single, quotes.

Return a string of the code without comments.

So this code:

"""this is
my awesome script
"""
# importing modules
import re

def hello(name):
    """my function docstring"""
    return f'hello {name}'  # my inline comment

... would result in:

import re

def hello(name):
    return f'hello {name}'

Good luck and keep calm and code in Python!

Login and get coding
go back Advanced level
Bitecoin 4X

144 out of 151 users completed this Bite.
Will you be the 145th person to crack this Bite?
Resolution time: ~67 min. (avg. submissions of 5-240 min.)
Our community rates this Bite 7.75 on a 1-10 difficulty scale.
» Up for a challenge? 💪

Focus on this Bite hiding sidebars, turn on Focus Mode.

Ask for Help